
var Results = {
    
    /**
     * Initializes results interface
     * 
     */
    init: function() {
        this.configUI();
    },
    
    /**
     * Sets up UI for results interface
     */
    configUI: function() {
        this.configProfile();
        this.configTransRows();
        this.configCreditModal();
        this.configRevertModal();
    },
    
    /**
     * Sets up Member Profile related interface
     */
    configProfile: function() {
        var updateField = function(field) {
            var url = $(field).data('url');
            var data = $(field).html();
                
            $(field).data('content', data).blur();
                
            Results.updateProfile(url, data);
        };
        
        $(".updatable").blur(function() {
            
            if( $(this).html() != $(this).data('content') ) {
                if( confirm("Content of field has changed. Do you want to save changes?") ) {
                    updateField(this);
                }
            }
            
            $(this).html( $(this).data("content") ).removeAttr("contenteditable").removeAttr("title").removeClass("editing");
            
        }).keydown(function(e) {
            if( e.keyCode == 13 ) {
                e.preventDefault();
                e.stopPropagation();
                
                updateField(this);
                
                return;
            }
        });
        
        $(".update_link").click(function() {
            var updatable = $(this).siblings(".updatable");
            
            updatable.addClass("editing").attr({
                contenteditable: true,
                title: "Hit ENTER to save changes, TAB to discard to changes"
            }).data({
                content: updatable.html()
            }).focus();
        });
    },
    
    /**
     * Sets up UI elements for the Transactions display on the right
     */
    configTransRows: function() {
        $(".cheque_row").hide();
        
        $(".revert_btn").live('click', function() {
            var tr = $(this).parents('tr');
            
            $("#trans_reversal_modal form").get(0).reset();
            $("#trans_reversal_modal").find('#pay_method').html( tr.find(".pay_method").html() );
            $("#trans_reversal_modal").find('#amount').html( tr.find(".amount").html() );
            $("#trans_reversal_modal").find('#transaction_debit_amt').val( tr.find(".amount").html() );
            $("#trans_reversal_modal").find("#transaction_id").val( tr.data('transaction-id') );
            
            $("#trans_reversal_modal").modal('show');
            setTimeout(function() {
                $("#trans_reversal_modal textarea").focus();
            }, 500);
        });
    },
    
    /**
     * Sets up UI elements for the Credit Account Modal
     */
    configCreditModal: function() {

        $('#amount_paid').live('keydown',function(event) {
            if(event.which == 8 || event.which == 37 || event.which == 40 || event.which == 38 || event.which == 39){
                //allow keys for backspace, arrow keys
            }
            else{
                if ((event.which != 190 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
                    //console.log('prevent')
                    event.preventDefault();
                }
            }
        });


        $("#payment_method").change(function() {
            if( $(this).val() == "cheque" ) {
                $(".cheque_row").show();
            }
        
            else {
                $(".cheque_row").hide();
            }
        });
        
        
        $("#credit_modal form").submit(function(e) {
            e.preventDefault();
            Results.creditAccount();
        });
        
        $('#credit_modal, #trans_reversal_modal').modal({
            backdrop: 'static',
            show: false,
            keyboard: true
        });
    },
    
    /**
     * sets up UI for teh revert transaction modal
     * @returns {undefined}
     */
    configRevertModal: function() {
        $("#trans_reversal_modal form").submit(function(e) {
            e.preventDefault();
            Results.revertTransaction();
        });
    },
    
    /**
     * Triggers steps to make AJAX call to credit student account
     */
    creditAccount: function() {
        var self = this;
        var query = $("#credit_modal form").serialize();
        var amount_tendered = parseFloat($("#credit_modal #amount_paid").val());
        var url = $("#credit_modal #credit_btn").attr("href");
        teller_credit_limit = parseFloat(teller_credit_limit);

        var receipt_data = {
            'pay_method':$("#credit_modal #payment_method option:selected").text(),
            'amount':amount_tendered,
            'payee':$("#credit_modal #payee_name").val(),
            'fon':$("#credit_modal #phone").val(),
            'address':$("#credit_modal #address").val(),
            'served_by':teller_serving,
            'bank':bank_name,
            'branch':branch_name
        }
        if(amount_tendered >= teller_credit_limit){
            //alert(amount_tendered);
            var r=window.confirm("You are about to credit more than the CREDIT LIMIT OF GHS "+teller_credit_limit+". Please make sure the value entered GHS "+amount_tendered+" is correct. An authorization will be required before account will be debited.");
            if (!r){
                return false;
            }
        }
            
        Results.disableCreditForm(true);
            
        $.ajax({
            type: 'post',
            url: url,
            data: query,
            success: function(data) {
                Results.disableCreditForm(false);
                $("#credit_modal").modal("hide");
                
                $("#trans_block").html(data);
                $("#account_balance").html("GHC " + $("#student_account_balance").val());

                self.showReceipt(receipt_data);
            },
            error: function() {
                Results.disableCreditForm(false);
            }
        });
    },


    showReceipt:function(data){

        $("#receipt_modal .bank_name_holder").html(data.bank);
        $("#receipt_modal .payment_method_holder").html(data.pay_method);
        $("#receipt_modal .amount_paid_holder").html("GHC " +data.amount);
        $("#receipt_modal .bank_branch_holder").html(data.branch);
        $("#receipt_modal .payee_name_holder").html(data.payee);
        $("#receipt_modal .phone_holder").html(data.fon);
        $("#receipt_modal .address_holder").html(data.address);

        $("#receipt_modal").modal("show");
    },
    
    /**
     * Enables/Disables the form elements on the Credit Account form
     * 
     * @param boolean disable
     * @returns void
     */
    disableCreditForm: function(disable) {
        if( disable ) {
            $("#credit_modal form :input").attr("disabled","disabled");
            $("#credit_modal #credit_btn").html("<i class='icon icon-spinner'></i> Processing").addClass("disabled");
        } 
        
        else {
            $("#credit_modal form :input").removeAttr("disabled");
            $("#credit_modal #credit_btn").html("Credit Account").removeClass("disabled");
            $("#credit_modal form").get(0).reset();
            $(".cheque_row").hide();
        }
    },
    
    /**
     * Triggers the AJAX call to make a transaction as requiring reversal
     */
    revertTransaction: function() {
        if( !confirm("You are about to revert this transaction and potentially refund the amount paid.\n\nClick OK to continue or CANCEL to return to previous screen")) {
            return;
        }
        
        var query = $("#trans_reversal_modal form").serialize();
        var url = $("#trans_reversal_modal form").attr("action");
        
        $.ajax({
            type: 'post',
            url: url,
            data: query,
            success: function(data) {
                $("#trans_reversal_modal").modal("hide");
                
                var obj = null;
                try {
                    obj = JSON.parse(data);
                } catch(e) {}
                
                if( obj != null && typeof obj.status != 'undefined' && obj.status == 'failed' ) {
                    Results.showMessage("Failed To Revert Transaction", obj.message);
                }
                else {
                    $("#trans_block").html(data);
                    $("#account_balance").html("GHC " + $("#student_account_balance").val());
                }
            },
            error: function(xhr) {
                console.log(xhr.responseText);
            }
        });
    },
    
    /**
     * Makes an AJAX call to update a specific student profile element
     * 
     * @param String url
     * @param String data
     * @returns object
     */
    updateProfile: function(url, data) {
        $.ajax({
            url: url,
            data: 'field=' + data,
            type: 'post',
            dataType: 'json',
            success: function(res) {
                
            },
            error: function(xhr) {
                console.log(xhr);
            }
        });
    },
    
    /**
     * Displays an alert message
     * 
     * @param {type} title
     * @param {type} message
     * @param {type} type
     * @returns {undefined}
     */
    showMessage: function(title, message, type) {
        $("#message_modal .modal-header h4").html(title);
        $("#message_modal .modal-body").html(message);
        
        $("#message_modal").modal('show');
    }
};

$(document).ready(function() {
    Results.init();
});
